<?php
/**
 *
 *   User:King
 *   Date:2021/12/10 10:53
 */
namespace app\bank_api\library;

use Firebase\JWT\JWT;
use think\Exception;

class Jwtclass
{
    //校验jwt权限API
    public static function verifyJwt($jwt)
    {
        $key = md5('jingshenwulian');
        // JWT::$leeway = 3;
        try {
            //$jwtAuth  包含所有包括用户信息
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            $result = [];
            if (!empty($authInfo['data'])) {
                $result = [
                    'status' => 1001,
                    'msg' => 'Token验证通过',
                    'data' => $authInfo['data']
                ];
            } else {
                $result = [
                    'status' => 1002,
                    'msg' => 'Token验证不通过,用户不存在'
                ];
            }
            return $result;
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            $result = [
                'status' => 1004,
                'msg' => 'Token无效'
            ];
            return $result;
        } catch (\Firebase\JWT\ExpiredException $e) {
            $result = [
                'status' => 1004,
                'msg' => 'Token过期'
            ];
            return $result;
        } catch (\Exception $e) {
            $result = [
                'status' => 1003,
                'msg' => $e->getMessage()
            ];
            return $result;
        }
    }

    public static function createJwt($staff)
    {
        $key = md5('jingshenwulian'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 604800; //过期时间 //一周过期
        $token = array(
            "data" => $staff ,
            "iss"  => "jingshenwulian",//签发组织
            "aud"  => "jingshenwulian", //签发作者
            "iat"  => $time,
            "nbf"  => $time,
            "exp"  => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }
}